package com.test.javafaq_gateway.service.impl;

import com.test.javafaq_commons.entity.Permission;
import com.test.javafaq_commons.entity.Role;
import com.test.javafaq_commons.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    RestTemplate restTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //获取用户信息  http://sys-service/v1/sys/demo
        String url = "http://sys-service/v1/auth/user?username={1}";
        User user = restTemplate.getForObject(url, User.class,username);
        if(user == null){
            throw new UsernameNotFoundException("登陆失败");
        }


        //查用户权限
        url = "http://sys-service/v1/auth/permissions?userId={1}";
        Permission[] permissions = restTemplate.getForObject(url,Permission[].class,user.getId());

        //查询角色
        url = "http://sys-service/v1/auth/roles?userId={1}";
        Role[] roles = restTemplate.getForObject(url,Role[].class,user.getId());

        if(permissions == null || roles ==null){
            throw new UsernameNotFoundException("缺失权限或角色");
        }

        String[] auths = new String[permissions.length + roles.length];
        int i = 0;
        for(Permission p:permissions){
            auths[i++] = p.getName();
        }
        for(Role r:roles){
            auths[i++] = r.getName();
        }

        //UserDetails
        UserDetails u = org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auths)
                //账号是否锁定
                .accountLocked(user.getLocked() == 1)
                //账号是否可用
                .disabled(user.getEnabled() == 0)
                .build();
        System.out.println("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuu = " + u);

        return u; //一定不要返回null
    }
}
